package com.wanghaixin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wanghaixin.dto.DataGridResult;
import com.wanghaixin.dto.QueryDTO;
import com.wanghaixin.dto.UserDTO;
import com.wanghaixin.exception.RException;
import com.wanghaixin.pojo.SysUser;
import com.wanghaixin.service.SysUserService;
import com.wanghaixin.utils.MD5Utils;
import com.wanghaixin.utils.R;
import com.wanghaixin.utils.ShiroUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Auther: 王海新
 * @Date: 2020/10/22 08:42
 * @Description: login登录Controller/用户模块
 */
@Controller
public class UserController {


    @Autowired
    private SysUserService sysUserService;

    //注入验证码配置文件
    @Autowired
    private DefaultKaptcha kaptcha;

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 11:04  2020/10/26
     * @Version: 1.0.0
     * @Description: 验证码配置
     */
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) {
        //缓存设置，设置不缓存
        response.setHeader("Cache-Control", "no-store,no-cache");
        //设置响应内容
        response.setContentType("image/jpg");
        //生成验证码
        String text = kaptcha.createText(); //文本
        //生成图片
        BufferedImage image = kaptcha.createImage(text);
        //验证码存储到shiro的session
        ShiroUtils.setKaptcha(text);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 21:06  2020/10/23
     * @Version: 1.0.0
     * @Description: 登录页面，数据检验
     */
    @RequestMapping("sys/login")
    @ResponseBody
    public R login(@RequestBody UserDTO userDTO) {
        //比对验证码
        String serverkaptcha = ShiroUtils.getKaptcha();
        if (!serverkaptcha.equalsIgnoreCase(userDTO.getCaptcha())) {
            return R.error("验证码错误");
        }

        Subject subject = SecurityUtils.getSubject();

        //使用md5来加密账户密码
        String newPass = MD5Utils.md5(
                userDTO.getPassword(), userDTO.getUsername(), 1024);
//将账户密码放到token中
        UsernamePasswordToken token = new UsernamePasswordToken(
                userDTO.getUsername(), newPass);
        //是否有记住我 的能力
        if (userDTO.isRememberMe()) {
            token.setRememberMe(true);
        }
        //subject有一个登录的能力，需要参数 token封装的账户密码
        subject.login(token);
        //会去调用自定义的realm 进行认证和授权

        return R.ok();
    }

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 20:39  2020/10/23
     * @Version: 1.0.0
     * @Description: 分页查询/搜索/排序
     */
    @RequestMapping("/sys/user/list")
    @ResponseBody
    public DataGridResult findUserByPage(QueryDTO queryDTO) {
        return sysUserService.findUserByPage(queryDTO);
    }

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 9:16  2020/10/25
     * @Version: 1.0.0
     * @Description: 接口/sys/user/export  不是导入json，直接是导excel文档
     * 所以@RequestMapping即可。利用response的流进行输出，不需要返回值
     */
    @RequestMapping("/sys/user/export")
    public void exportUser(HttpServletResponse response) {
        Workbook workbook = sysUserService.exportUser();
        try {
            //设置响应头
            response.setContentType("application/octet-strem");//所有文件都支持

            //这里出现问题，员工信息没有设置上去

            String fileName = "员工信息.xls";
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("content-disposition", "attachment:filename=" + fileName);
            //文件下载
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 10:43  2020/10/28
     * @Version: 1.0.0
     * @Description: 退出系统
     */
    @RequestMapping("/logout")
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

    /*********************************************************************************************************************
     * @Author: 王海新
     * @Date: 11:09  2020/10/28
     * @Version: 1.0.0
     * @Description: 动态菜单模块获 取用户信息接口
     */
    @RequestMapping("sys/user/info")
    @ResponseBody
    public R userinfo() {
        //可以从shiro中获取
        SysUser userEntity = ShiroUtils.getUserEntity();
        return R.ok().put("user", userEntity);

    }

}
